import axios from '@/util/request'
import {tryCatch} from '@dcloudio/uni-h5/src/core/helpers/catch'

function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = + new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments)   //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

function debounce(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 300
  }
  let timeout = null
  // 返回新的函数
  return function () {
    if(timeout !== null)  clearTimeout(timeout);
    timeout = setTimeout(()=>{
      fn.apply(this, arguments)
    },gapTime);
  }
}


function getCharMax(str) {
  let acc = []
  var t = str
  while (t) { // if this l exists
    var _st = t.substr(0, 1);
    var m = t.replace(new RegExp(_st, 'gi'), '');
    let result = {
      name: _st,
      length: t.length - m.length
    };
    acc.push(result)
    t = m;
  }
  acc.sort((a,b)=>{ return a.length-b.length})//升序
  return acc;
}

function getCharMax2(str) {
  var t = str
  let result = {}
  while (t) { // if this l exists
    var _st = t.substr(0, 1);
    var m = t.replace(new RegExp(_st, 'gi'), '');
    result[_st] = {
      name: _st,
      length: t.length - m.length
    }
    t = m;
  }
  return result;
}


function sameTreatment(char1,char2) {
  if(char1 === 'E' && char2 === 'I') return 'I'
  if(char1 === 'S' && char2 === 'N') return 'N'
  if(char1 === 'T' && char2 === 'F') return 'F'
  if(char1 === 'J' && char2 === 'P') return 'P'
}

function checkLogin() {
  return new Promise((resolve,reject) => {
    uni.checkSession({
      success() {
        console.log(`session未过期`);
        resolve({code: 0})

      },
      async fail() {
        console.log(`session已过期，需要重新登录`);
        try {
          let loginRes = await login()
          resolve(loginRes)
        }
        catch (e) {
          reject(e)
        }
      },
    });
  })
}

const videoAd = uni.createRewardedVideoAd({
  adUnitId: '14322h55hjdbc1852l'
})

function playAdvertisement() {
  return new Promise((reslove,reject) => {
    videoAd.show()
      .then(() => {
		console.log("广告组件显示")
        reslove(videoAd)
      })
      .catch(err => {
        console.log("广告组件出现问题", err);
        // 可以手动加载一次
        videoAd.load().then(() => {
		  
          reslove(videoAd)
          // 加载成功后需要再显示广告
          return videoAd.show();
        }).catch(err => {
          reject(err)
        });
      });
  })
}


function login() {
  return new Promise((resolve,reject) => {
    uni.login({
      provider: 'toutiao',
      success: res => {
        var codeObj = res;
        uni.getUserInfo({
          success: async res => {
            try {
              let loginRes = await axios.post('https://tt.yugetj.com/api/User/Login',{...codeObj, ...res.userInfo })
              uni.setStorageSync('openid', loginRes.data.data.openid);
              uni.setStorageSync('session_key', loginRes.data.data.sessionKey)
              resolve({
                ...res
              })
            }
            catch (e) {
              reject(e)
            }
          },
          fail(e) {
            console.log(`getUserInfo 调用失败`, res);
            reject(e)
          }
        })
      }
    })
  })
}

module.exports = {
  throttle:throttle,
  debounce:debounce,
  getCharMax: getCharMax,
  sameTreatment:sameTreatment,
  getCharMax2:getCharMax2,
  checkLogin: checkLogin,
  playAdvertisement:playAdvertisement,
  login: login,
}
